<template>
  <div class="tongjibb-page">
    <el-card class="mb-20">
      <template #header>
        <div class="tongjibb-header">
          <span>{{ pageTitle }}</span>
          <div class="query-info">
            <span v-if="route.query.type">类型: {{ route.query.type }}</span>
            <span v-if="route.query.title">标题: {{ route.query.title }}</span>
          </div>
        </div>
      </template>
      
      <!-- 查询条件 -->
      <el-row :gutter="16" class="mb-10">
        <el-col v-if="show_nian" :span="6">
          <el-date-picker 
            v-model="nian" 
            type="year" 
            placeholder="选择年份" 
            style="width: 100%;" 
            @change="bindDateChangen" 
          />
        </el-col>
        <el-col v-if="show_yue" :span="6">
          <el-date-picker 
            v-model="yue" 
            type="month" 
            placeholder="选择月份" 
            style="width: 100%;" 
            @change="bindDateChangey" 
          />
        </el-col>
        <el-col v-if="show_ri" :span="6">
          <el-date-picker 
            v-model="ri" 
            type="date" 
            placeholder="选择日期" 
            style="width: 100%;" 
            @change="bindDateChanger" 
          />
        </el-col>
        <el-col v-if="show_ywy" :span="6">
          <el-input 
            v-model="ygxm" 
            placeholder="查询业务员" 
            readonly 
            @focus="popupVisible = true" 
          />
        </el-col>
        <el-col :span="6">
          <el-input v-model="khmc" placeholder="客户名称" clearable />
        </el-col>
        <el-col :span="6">
          <el-input v-model="sbbh" placeholder="设备编号" clearable />
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="getData_index">查询</el-button>
        </el-col>
      </el-row>

      <!-- 统计数据展示 -->
      <div class="statistics-content">
        <div v-if="loading" class="loading-wrapper">
          <el-skeleton :rows="5" animated />
        </div>
        
        <div v-else-if="objing && objing.length" :class="['hp_tongji', `hp_${dtype}`]">
          <div v-for="(oitem, index) in objing" :key="index" :class="oitem.cssbt">
            <div 
              v-for="(titem, txh) in oitem.shuzu" 
              :key="txh" 
              :class="['td', titem.bt === '设备自编号' ? 'device-code' : '']" 
              :style="titem.bt === '设备自编号' ? 'max-width: 320px;' : ''"
            >
              <div class="ellipsis-text1" v-if="isNameColonColonFormat(titem.name)">
                {{ removeLineBreaks(titem.name) }}
              </div>
              <div class="ellipsis-text" v-else v-html="formatNameText(titem.name)"></div>
            </div>
          </div>
        </div>
        
        <div v-else class="no-data">
          <el-empty description="暂无数据" />
        </div>
      </div>
    </el-card>

    <!-- 业务员选择弹窗 -->
    <el-dialog v-model="popupVisible" title="请选择业务员" width="500px" :close-on-click-modal="true">
      <el-row :gutter="8" class="mb-10">
        <el-col :span="16">
          <el-input v-model="keyinput" placeholder="查询" clearable />
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="cxDanCanShu">查询</el-button>
        </el-col>
      </el-row>
      
      <div class="ywy-list">
        <div 
          v-for="(item, index) in ywyshuzu" 
          :key="index" 
          class="ywy-item" 
          @click="selectYwy(item)"
        >
          {{ item.xingming }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import request, { getApiPath } from '@/utils/request'
import { Base64 } from 'js-base64'

const route = useRoute()

// 响应式数据
const loading = ref(false)
const objing = ref([])
const dtype = ref('table')
const nian = ref(new Date())
const yue = ref(new Date())
const ri = ref(new Date())
const khmc = ref('')
const sbbh = ref('')
const ygxm = ref('')
const popupVisible = ref(false)
const keyinput = ref('')
const ywyshuzu = ref([])

// 显示控制
const show_nian = ref(true)
const show_yue = ref(true)
const show_ri = ref(true)
const show_ywy = ref(true)

// 计算属性
const pageTitle = computed(() => {
  return route.query?.title || route.query?.category || '统计报表'
})

// 获取统计数据 - 根据URL参数动态构建请求
const getData_index = async () => {
  loading.value = true
  try {
    console.log('=== 统计报表请求开始 ===')
    console.log('路由参数:', route.query)
    
    const openid = localStorage.getItem('openid') || "17524180246839845722"
    const yewuy = localStorage.getItem('username') || ''

    // 根据路由参数动态设置请求参数
    const bs64_cs = {
      openid,
      yewuy,
      // 从路由参数中获取 type，这个来自菜单的传参
      dtype: route.query?.type || route.query?.dtype || 'yue_meirizjt',
      // 时间参数
      yue: yue.value ? formatYearMonth(yue.value) : formatYearMonth(new Date()),
      nian: nian.value ? new Date(nian.value).getFullYear() : new Date().getFullYear(),
      ri: ri.value ? formatDate(ri.value) : formatDate(new Date()),
      // 查询条件
      khmc: khmc.value,
      sbbh: sbbh.value,
      ygxm: ygxm.value
    }

    const cs = {
      ctype: 'zlxt_tongjibaobiao', // 统一使用这个 ctype
      bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
      bs64_obj: '',
      bs64_list: '',
      bs64_obj_zhub: '',
      ids: '',
      faid: 0
    }

    console.log('统计报表请求参数:', cs)
    console.log('bs64_cs解码:', bs64_cs)

    const res = await request.post('https://vue.haozskj.com/xcx/ajax/Ajax_apppost.ashx', { canshu: cs })
    
    console.log('统计报表响应:', res)

    if (res && res.leixing === 'ok') {
      objing.value = res.objing || []
      dtype.value = res.dtype || 'table'
      console.log('统计数据获取成功:', objing.value)
    } else {
      console.log('统计数据获取失败:', res)
    }
  } catch (error) {
    console.log('获取统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询业务员参数
const cxDanCanShu = async () => {
  try {
    const openid = localStorage.getItem('openid') || "17524180246839845722"

    const bs64_cs = {
      openid,
      wtype: 'ywy',
      key: keyinput.value
    }

    const cs = {
      ctype: 'app_xuanze_canshu',
      bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
      bs64_obj: '',
      bs64_list: '',
      ids: ''
    }

    const res = await request.post(getApiPath(cs.ctype), { canshu: cs })

    if (res && res.leixing === 'ok') {
      ywyshuzu.value = res.shuzu || []
    }
  } catch (error) {
    console.log('查询业务员失败:', error)
  }
}

// 选择业务员
const selectYwy = (item) => {
  ygxm.value = item.xingming
  popupVisible.value = false
}

// 日期变化处理
const bindDateChangen = () => {
  getData_index()
}

const bindDateChangey = () => {
  getData_index()
}

const bindDateChanger = () => {
  getData_index()
}

// 工具函数
const formatDate = (date) => {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const formatYearMonth = (date) => {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  return `${year}-${month}`
}

const isNameColonColonFormat = (name) => {
  return name && name.includes('::')
}

const removeLineBreaks = (text) => {
  return text ? text.replace(/\n/g, ' ').replace(/\r/g, '') : ''
}

const formatNameText = (text) => {
  if (!text) return ''
  return text.replace(/\n/g, '<br>')
}

// 初始化
onMounted(() => {
  console.log('=== 统计报表页面初始化 ===')
  console.log('当前路由参数:', route.query)
  getData_index()
})
</script>

<style scoped>
.tongjibb-page {
  padding: 20px;
}

.tongjibb-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.query-info {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #666;
}

.statistics-content {
  margin-top: 20px;
}

.loading-wrapper {
  padding: 20px;
}

.hp_tongji {
  min-height: 200px;
}

.hp_table .td {
  padding: 8px 12px;
  border: 1px solid #e4e7ed;
  background: #fff;
  display: table-cell;
  vertical-align: middle;
}

.hp_table .cssbt {
  display: table-row;
}

.hp_table .cssbt:nth-child(even) {
  background-color: #f9f9f9;
}

.hp_table .cssbt:hover {
  background-color: #f0f8ff;
}

.device-code {
  max-width: 320px;
  word-break: break-all;
}

.ellipsis-text,
.ellipsis-text1 {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ellipsis-text1 {
  max-width: 100%;
}

.ywy-list {
  max-height: 300px;
  overflow-y: auto;
}

.ywy-item {
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.ywy-item:hover {
  background-color: #f5f5f5;
}

.no-data {
  text-align: center;
  padding: 40px;
}

.mb-20 {
  margin-bottom: 20px;
}

.mb-10 {
  margin-bottom: 10px;
}
</style>
